package com.km.web;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.km.entity.City;
import com.km.mapper.CityMapper;
import com.km.service.ExampleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * <p></p>
 * Created by zhezhiyong@163.com on 2017/8/29.
 */
@RestController
//@Configuration
public class ExampleController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate template;
    @Resource
    private ExampleService exampleService;
    @Resource
    private CityMapper cityMapper;

    public static TransmittableThreadLocal<String> parent = new TransmittableThreadLocal<String>();

    @RequestMapping("/a")
    public String a(HttpServletRequest request) throws InterruptedException {
        String id = request.getParameter("id");
        logger.info("未设置值:{}", parent.get());
        parent.set(id);
        logger.info("in /a"); // arbitrary log message to show integration works
        MDC.put("test", "this test thread param transmit");
        Random random = new Random();
        exampleService.testThreadLocal();
        Thread.sleep(random.nextInt(1000));

        cityMapper.getAll();
        // make a relative request to the same process
        StringBuffer nextUrl = request.getRequestURL();
        nextUrl.deleteCharAt(nextUrl.length() - 1).append('b');
        return template.getForObject(nextUrl.toString(), String.class);
    }

    @RequestMapping("/b")
    public String b() throws InterruptedException {
        parent.set("haha");
        logger.info("in /b"); // arbitrary log message to show integration works
        Random random = new Random();
        Thread.sleep(random.nextInt(1000));
        return "b";
    }

    @GetMapping("/mysql")
    public String mysql() throws InterruptedException {
        logger.info("in /mysql"); // arbitrary log message to show integration works
        Thread.sleep(1000);
        cityMapper.getAll();
        City city = new City();
        city.setName("福建省");
        city.setState("福州市");
        int r = cityMapper.insert(city);
        System.out.println(r);
        Thread.sleep(500);
        city.setState("莆田市");
        r = cityMapper.update(city);
        System.out.println(r);
        Thread.sleep(1000);
        r = cityMapper.delete(city);
        System.out.println(r);
        Thread.sleep(2000);
        return "mysql";
    }
}
